package com.ldx.future;

/**
 * @author lidexin
 * @create 2021-10-17 20:10
 */


import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 异步调用：
 */
public class Demo01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //没用返回值的 runAsync 异步回调
//        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
//            try {
//                TimeUnit.SECONDS.sleep(2);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            System.out.println(Thread.currentThread().getName()+"runAsync=>Void");
//        });
//        System.out.println("11111");
//        completableFuture.get(); // 获取阻塞执行结果

            //有返回值的supplyAsync 异步回调
            CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(()->{
                System.out.println(Thread.currentThread().getName()+"supplyAsync=>Integer");
                int i = 10/0;
                return 1024;
            });

        System.out.println(completableFuture.whenComplete((t, u)-> {
            System.out.println("t=>"+t);//正常的返回数据
            System.out.println("u=>"+u);//错误信息：java.util.concurrent.CompletionException:
        }).exceptionally((e)->{
            System.out.println(e.getMessage());
            return 233;
        }).get());
        }
    }

